import path from 'path'
import { Command } from 'commander';
import inquirer from 'inquirer';
import { fileURLToPath } from 'url';
import fs from 'fs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const { version, name } = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf8'));

 // 如果 WechatEveryDay.memory-card.json 文件存在，删除
 if (fs.existsSync(path.resolve(__dirname, '../WechatEveryDay.memory-card.json'))) {
    fs.unlinkSync(path.resolve(__dirname, '../WechatEveryDay.memory-card.json'));
}

process.on('uncaughtException', (err) => {
    if (err.code === 'ERR_ASSERTION') {
        console.error('❌❌❌ 捕获到断言错误: ', err.message);
    } else {
        console.error('❌❌❌ 捕获到未处理的异常: ', err);
    }
    // if (fs.existsSync('WechatEveryDay.memory-card.json')) {
    //   fs.unlinkSync('WechatEveryDay.memory-card.json')
    // }
});

const questions = [{
    type: 'list',
    name: 'serviceType', //存储当前问题回答的变量key，
    message: '请先选择服务类型',
    choices: [{
            name: 'ChatGPT',
            value: 'ChatGPT'
        },
        {
            name: 'Kimi',
            value: 'Kimi'
        },
        {
            name: 'Xunfei',
            value: 'Xunfei'
        },
        {
            name: 'Doubao',
            value: 'Doubao'
        },
    ]
}];

export const generator = onStart => {
    const program = new Command(name);
    program
        .alias('we')
        .description('🤖一个基于 WeChaty 结合AI服务实现的微信机器人。')
        .version(version, '-v, --version, -V')
        .option('-s, --serve <type>', 'port type', '')
        // .option('-p, --proxy <url>', 'proxy url', '')
        .action(function () {
            const { serve } = this.opts();
            // const args = this.args;
            if (!serve) {
                inquirer
                    .prompt(questions)
                    .then((res) => {
                        onStart(res.serviceType);
                    })
                    .catch((error) => {
                        console.log('🚀error:', error)
                    });
            } else {
                onStart(serve);
            }
        });
    program.parse();
};